package com.kitty.game.npc.facade;

import com.kitty.common.cache.RedisService;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.role.model.Role;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.npc.message.*;
import com.kitty.game.npc.service.NewNpcService;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.game.role.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.text.MessageFormat;
import java.util.Random;
//后加
import com.kitty.game.npc.message.ReqCloseMenu;
import com.kitty.game.npc.message.ReqNpcTalk;
import com.kitty.game.npc.message.ReqOpenMenu;
import com.kitty.game.npc.message.ReqStartWuxing;
import com.kitty.game.npc.message.ReqWuxingBank;
import com.kitty.game.npc.message.RespNpcLeave;

/**
 * 处理NPC请求相关的Controller
 */
@Controller
@Slf4j
public class NewNpcController {

    @Autowired
    RedisService redisService;
    /**
     * 请求NPC内容，一般在点击NPC时请求
     */
    @RequestMapping
    public void reqNpcContent(IoSession session, ReqOpenMenu reqOpenMenu) {
        Role role = SessionUtils.getRoleBySession(session);
        log.info("请求NPC内容 roleId: {}, npcId: {}", role.getRoleId(), reqOpenMenu.getNpcId());
        SpringUtils.getBean(NewNpcService.class).requestNpcContent(role, reqOpenMenu.getNpcId());
    }

    /**
     * 请求点击NPC按钮
     */
    @RequestMapping
    public void reqClickNpcButton(IoSession session, ReqNpcTalk reqNpcTalk) {
        Role role = SessionUtils.getRoleBySession(session);
        if (reqNpcTalk.getMsg().startsWith("wenti")){
            log.error("内容内容内容内容=={}",reqNpcTalk.getMsg(),session.getAttribute("taishanglaoj_wenti"));
            session.setAttribute("taishanglaoj_huida",reqNpcTalk.getMsg());
        }else {
            SpringUtils.getBean(NewNpcService.class).clickNpcButton(role, reqNpcTalk.getNpcId(), reqNpcTalk.getMsg(), reqNpcTalk.getPara());
        }
    }

    /**
     * 五行竞猜开始 启动转盘
     *
     * @param session
     * @param reqStartWuxing
     */

    @RequestMapping
    public void startWuxing(IoSession session, ReqStartWuxing reqStartWuxing) {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Role role = SessionUtils.getRoleBySession(session);

        int score = reqStartWuxing.getAmount();
        if (score <= 0) {
            return;
        }
        String wuxing_xiaohao = DataCache.REDIS_DATA.get("wuxing_xiaohao");
        roleService.subCountByteType(role,score, wuxing_xiaohao);
        byte type = reqStartWuxing.getChoice();
        String content = roleService.wuxing.get(role.getName());
        String strType = type + "";
        String shengxiao;
        String wuxing;
        if (strType.length() == 2) {
            shengxiao = strType.substring(0, 1);
            wuxing = strType.substring(1, strType.length());
        } else if (strType.length() == 3) {
            shengxiao = strType.substring(0, 2);
            wuxing = strType.substring(2, strType.length());
        } else {
            return;
        }
        Random random = new Random();
        String prizeZodiac;//生肖
        String prizeWuXing;//五行

        int multi = 1;

        if (random.nextInt(40) + 1 == 1) {
            prizeZodiac = shengxiao;
            multi *= 12;
        } else {
            while (true) {
                int r = random.nextInt(12) + 1;
                if (r != Integer.parseInt(shengxiao)) {
                    prizeZodiac = r + "";
                    break;
                }

            }
        }

        if (random.nextInt(10) + 1 == 1) {
            prizeWuXing = wuxing;
            multi *= 5;
        } else {
            while (true) {
                int r = random.nextInt(5) + 1;
                if (r != Integer.parseInt(wuxing)) {
                    prizeWuXing = r + "";
                    break;
                }
            }
        }

        // 鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪
        String[] shenxiaos = "鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪".split("、");
        String[] wuxins = "金、木、水、火、土".split("、");
        if (content != null) {
            // name##五行##生肖
            String[] strings = content.split("##");
            multi = 1;
            String tempShenxiao = "";
            for (int i = 0; i < shenxiaos.length; i++) {
                String temp = shenxiaos[i];
                if (strings[2].equals(temp)) {
                    tempShenxiao = i+1 + "";
                    break;
                }
            }
            prizeZodiac = tempShenxiao;
            if (tempShenxiao.equals(shengxiao)) {
                multi *= 12;
            }
            String tempWuxing = "";
            for (int i = 0; i < wuxins.length; i++) {
                String temp = wuxins[i];
                if (strings[1].equals(temp)) {
                    tempWuxing = i +1+ "";
                    break;
                }
            }
            prizeWuXing = tempWuxing;
            if (tempWuxing.equals(wuxing)) {
                multi *= 5;
            }
            log.error("五行=={}=={}=={}=={}=={}", content, shengxiao, tempShenxiao,wuxing,tempWuxing);
        }
        //最后判断是否为1
        log.error("选择生肖=={},选择五行=={},==中奖生肖=={},中奖五行=={},倍数=={}", shengxiao, wuxing, prizeZodiac, prizeWuXing, multi);
        if (multi == 1) { //没有中奖
            multi = 0;
        }
        int giftMoney = score * multi;
        if (multi > 0) {
//            long wuxinScore = role.getWuxingBankMoney();
//            long total = wuxinScore + giftMoney;
//            if (total > 2000000000) {
//                total = 2000000000;
//            }
//            total = Math.max(total, 0);
//            role.setWuxingBankMoney((int) total);
            SchedulerManager.getInstance().schedule(() -> roleService.addCountByteType(role,giftMoney,wuxing_xiaohao), 8000);

            String msg;
            String sx = shenxiaos[Integer.parseInt(shengxiao)-1];
            String wx = wuxins[Integer.parseInt(wuxing)-1];
            if (multi == 60) {
                msg = MessageFormat.format("真是好运气啊！#Y{0}#n在五行竞猜活动中猜中了#R五行"+wx+"生肖"+sx+"#n，获得了#R"+giftMoney+wuxing_xiaohao+"#n的奖励！", role.getName());
            } else if (multi == 12) {
                msg = MessageFormat.format("真是好运气啊！#Y{0}#n在五行竞猜活动中猜中了#R生肖"+sx+"#n，获得了#R"+giftMoney+wuxing_xiaohao+"#n的奖励！", role.getName());
            } else {
                msg = MessageFormat.format("真是好运气啊！#Y{0}#n在五行竞猜活动中猜中了#R五行"+wx+"#n，获得了#R"+giftMoney+wuxing_xiaohao+"#n的奖励！", role.getName());
            }
            SpringUtils.getChatService().sendAdnotice(msg);
        }
        RespOpenGuess respOpenGuess = new RespOpenGuess();
        respOpenGuess.setFlag((byte) 1);//播放动画
        respOpenGuess.setMoney(giftMoney);//本次中奖所得
        respOpenGuess.setSurlus(String.valueOf(0));//总存款
        respOpenGuess.setOverflow("0");
        respOpenGuess.setAmount(score);
        respOpenGuess.setChoice(type); //选择类型
        respOpenGuess.setPrize(Byte.parseByte(prizeZodiac + prizeWuXing)); //中奖类型
        respOpenGuess.setLeftCount((byte) 99);
        MessagePusher.pushMessage(session, respOpenGuess);
        role.save();
        roleService.wuxing.remove(role.getName());
    }

    /**
     * 关闭NPC对话
     */
    @RequestMapping
    public void closeMenu(IoSession session, ReqCloseMenu reqCloseMenu) {
        //五行竞猜更新积分数量
        Role role = SessionUtils.getRoleBySession(session);
        RespNpcLeave respNpcLeave = new RespNpcLeave();
        respNpcLeave.setNpcId(reqCloseMenu.getNpcId());
        MessagePusher.pushMessage(session, respNpcLeave);
    }

    /**
     * 五行取款
     *
     * @param session
     * @param reqWuxingBank
     */
    @RequestMapping
    public void wuxingBank(IoSession session, ReqWuxingBank reqWuxingBank) {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Role role = SessionUtils.getRoleBySession(session);
        int DBWuxingMoney = role.getWuxingBankMoney();
        if (DBWuxingMoney <= 0) {
            return;
        }
        if (true){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("不能提取。"));
            return;
        }
        int DBMoney = role.getMoney();
        if (DBMoney >= 2000000000) {
            return;
        }
        int tiquMoney = 0;
        if (((long) DBMoney) + ((long) DBWuxingMoney) > 2000000000) {
            tiquMoney = 2000000000 - DBMoney;
        } else {
            tiquMoney = DBWuxingMoney;
        }
        role.setWuxingBankMoney(DBWuxingMoney - tiquMoney);
        
        roleService.addMoney(role, tiquMoney);


        MessagePusher.pushMessage(session, new RespIconCartoon("金钱"));

        RespOpenGuess respOpenGuess = new RespOpenGuess();
        respOpenGuess.setFlag((byte) 0);
        respOpenGuess.setMoney(0);  //未提取金钱
        respOpenGuess.setSurlus(0 + "");
        respOpenGuess.setOverflow("0");
        respOpenGuess.setAmount(0);
        respOpenGuess.setChoice((byte) 0);
        respOpenGuess.setPrize((byte) 0);
        respOpenGuess.setLeftCount((byte) SpringUtils.getActivityService().getRemainCount(role, ActivityType.XU_XING_JING_CAI));
        MessagePusher.pushMessage(role, respOpenGuess);
        String msg = AsktaoUtil.getMoneyFormat(tiquMoney);

        RespNotifyMiscEx respNotifyMiscEx = new RespNotifyMiscEx();
        respNotifyMiscEx.setMsg("你提取了" + msg + "#n文钱。");
        respNotifyMiscEx.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
        MessagePusher.pushMessage(session, respNotifyMiscEx);

    }
}
